import threading
import time
import numpy as np
import soundcard as sc
from typing import Dict, List, Optional, Callable, Any  # 添加 Any
import queue


class MultiChannelAudioEngine:
    def __init__(self, device_manager):
        self.device_manager = device_manager
        self.is_running = False
        self.processing_threads = {}
        self.sample_rate = 44100
        self.buffer_size = 512

    def start_processing(self, processing_graphs: Dict[int, callable]):
        """启动多路音频处理"""
        if self.is_running:
            return

        self.is_running = True

        # 为每个输入通道创建处理线程
        for input_id, processing_func in processing_graphs.items():
            thread = threading.Thread(
                target=self._processing_loop,
                args=(input_id, processing_func)
            )
            self.processing_threads[input_id] = thread
            thread.start()

    def stop_processing(self):
        """停止所有音频处理"""
        self.is_running = False
        for thread in self.processing_threads.values():
            thread.join()
        self.processing_threads.clear()

    def _processing_loop(self, input_id: int, processing_func: callable):
        """单路音频处理循环"""
        try:
            # 获取输入输出设备
            input_device = self.device_manager.get_input_device(input_id)
            output_device = self.device_manager.get_output_device(input_id)

            if not input_device or not output_device:
                print(f"输入或输出设备未配置: 输入ID {input_id}")
                return

            with input_device.recorder(samplerate=self.sample_rate,
                                       channels=2,
                                       blocksize=self.buffer_size) as mic, \
                    output_device.player(samplerate=self.sample_rate,
                                         channels=2,
                                         blocksize=self.buffer_size) as spk:

                while self.is_running:
                    # 读取音频数据
                    audio_data = mic.record(numframes=self.buffer_size)

                    # 处理音频数据
                    processed_data = processing_func(audio_data, input_id)

                    # 播放处理后的音频
                    spk.play(processed_data)

        except Exception as e:
            print(f"音频处理错误 (输入ID {input_id}): {e}")

    def get_available_input_ids(self) -> List[int]:
        """获取已配置的输入ID列表"""
        if self.device_manager:
            return list(self.device_manager.input_mapping.keys())
        return []

    def get_available_output_ids(self) -> List[int]:
        """获取已配置的输出ID列表"""
        if self.device_manager:
            return list(self.device_manager.output_mapping.keys())
        return []